package com.zoe.onelink.dubbo.mvc;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.stream.Collectors;

public class ServiceHandlerMapping extends RequestMappingInfoHandlerMapping {

    private RequestMappingInfo.BuilderConfiguration config = new RequestMappingInfo.BuilderConfiguration();

    /**
     * 支持DubboService注解的类
     * @param beanType
     * @return
     */
    @Override
    protected boolean isHandler(Class<?> beanType) {
        return (AnnotatedElementUtils.hasAnnotation(beanType, DubboService.class));
    }

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {

        String param = Arrays.stream(method.getParameters()).map(Parameter::getName).collect(Collectors.joining("-"));
        RequestMappingInfo.Builder builder = RequestMappingInfo
                .paths(String.join("/", "dubbo", handlerType.getSimpleName(), method.getName(), param))
                .consumes(MediaType.APPLICATION_JSON_VALUE)
                .methods(RequestMethod.POST);
        return builder.options(this.config).build();
    }

    /**
     * 保证自定义的映射优先处理
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
